package cloud.xlh.my_system.service.impl;

import cloud.xlh.my_system.common.CommonConstant;
import cloud.xlh.my_system.common.GenerateConstant;
import cloud.xlh.my_system.common.SystemConstant;
import cloud.xlh.my_system.common.response.Response;
import cloud.xlh.my_system.mapper.GenTableMapper;
import cloud.xlh.my_system.mapper.GenerateMapper;
import cloud.xlh.my_system.pojo.GenTable;
import cloud.xlh.my_system.pojo.GenTableColumn;
import cloud.xlh.my_system.pojo.Project;
import cloud.xlh.my_system.service.GenTableService;
import cloud.xlh.my_system.service.GenerateService;
import cloud.xlh.my_system.service.ProjectService;
import cloud.xlh.my_system.utils.CharsetKit;
import cloud.xlh.my_system.utils.StringUtil2;
import cloud.xlh.my_system.utils.VelocityInitializer;
import cloud.xlh.my_system.utils.VelocityUtils;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : code-generator
 * @ Author: XuLeHuang
 * @ Date: 2022/6/20 12:41
 * @ Description:
 */
@Service
@Transactional
public class GenerateServiceImpl implements GenerateService {
    @Autowired
    private GenTableMapper genTableMapper;
    @Autowired
    private ProjectService projectService;
    @Override
    public Response<String> generatorCode(String tableName , String projectId) {
        //表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);

        //子表信息
        setSubTable(table);

        //外键信息
        setPkColumn(table);

        //复制VelocityInitializer类
        VelocityInitializer.initVelocity();

        //复制VelocityUtils工具类
        VelocityContext context = VelocityUtils.prepareContext(table);

        //生成哪些文件，tplCategory：crud
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());

        for (String template : templates) {
            if (!StringUtil2.contains(template, "sql.vm")) {
                StringWriter sw = new StringWriter();
                //例如：vm/java/domain
                Template tpl = Velocity.getTemplate(template, SystemConstant.UTF8);
                tpl.merge(context, sw);
                try {
                    Project project = projectService.findProjectByProjectId(projectId);
                    table.setGenPath(project.getRootPath());
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                } catch (IOException e) {
                    //throw new BusinessException("渲染模板失败，表名：" + table.getTableName());
                }
            } else if (StringUtil2.contains(template, "sql.vm")) {
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, SystemConstant.UTF8);
                tpl.merge(context, sw);
                System.out.println("生成的sql:--------\n" + sw);
            }
        }
        return Response.success("代码生成成功");
    }
    /**
     * 获取代码生成地址
     *
     * @param table    业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template) {
        String genPath = table.getGenPath();
        if (StringUtil2.equals(genPath, CommonConstant.SLASH)) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
    }

    /**
     * 设置主子表信息
     *
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table) {
        String subTableName = table.getSubTableName();
        if (StringUtil2.isNotEmpty(subTableName)) {
            table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table) {
        for (GenTableColumn column : table.getColumns()) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtil2.isNull(table.getPkColumn())) {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenerateConstant.TPL_SUB.equals(table.getTplCategory())) {
            for (GenTableColumn column : table.getSubTable().getColumns()) {
                if (column.isPk()) {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtil2.isNull(table.getSubTable().getPkColumn())) {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

}
